﻿using System;
using System.Collections.Generic;
using System.Linq;
using ERP.Common.Model;

namespace ERP.Common.Extensions
{
    public static class CollectionExt
    {
        #region 判断集合是否为空

        public static bool IsNullOrEmpty<T>(this ICollection<T> source)
        {
            return source == null || source.Count <= 0;
        }

        #endregion

        #region 判断Guid类型是否为Empty
        public static bool IsEmpty(this Guid guid)
        {
            return guid == Guid.Empty;
        }
        #endregion

        #region 根据实体属性自定义去重

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector)
        {
            var seenKeys = new HashSet<TKey>();
            foreach (var element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

        #endregion

        #region 分页扩展方法

        public static PagedResultModel<TEntity> ApplyToPage<TEntity>(this ICollection<TEntity> source, int pageIndex,
            int pageSize, int totalCount)
        {
            var page = new PageWithTotalModel
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalCount = totalCount
            };
            return new PagedResultModel<TEntity>(source.ToList(), page);
        }
        #endregion

        #region 获取所有下级


        public static IEnumerable<SimpleTreeModel> GetSons(IList<SimpleTreeModel> list, Guid parentId)
        {
            var query = list.Where(p => p.Id == parentId);
            return query.Concat(GetSonList(list, parentId));
        }

        private static IEnumerable<SimpleTreeModel> GetSonList(IList<SimpleTreeModel> list, Guid parentId)
        {
            var query = list.Where(p => p.ParentId == parentId).ToList();
            return query.Concat(query.SelectMany(t => GetSonList(list, t.Id)));
        }

        #endregion

        #region 获取所有上级

        public static IEnumerable<SimpleTreeModel> GetFatherList(IList<SimpleTreeModel> list, Guid id)
        {
            var query = list.Where(p => p.Id == id).ToList();
            return query.Concat(query.SelectMany(t => GetFatherList(list, t.ParentId)));
        }

        #endregion
    }
}